import { CSSProperties, memo, useCallback, useState } from 'react';
import type { FC, PropsWithChildren } from 'react';
import { Link } from 'react-router-dom';
import { Button, Form, Input, message, Modal, Select, Table, Tag } from 'antd';
import { ColumnsType } from 'antd/es/table';
import {
  resDeleteOrders,
  resOrders,
  resOrdersPost,
  resOrdersReceive,
} from '@/services/orders';
import { DeleteTwoTone } from '@ant-design/icons';
import { useAntdTable } from 'ahooks';
import { isNumber } from 'lodash';
import { validateMessage } from '@/components/AddressFormModal';
import {
  itemStyle,
  orderNoStyle,
  style,
} from '@/pages/Profile/components/MyOrders';
import { formatTime, formatUrl } from '@/utils/format';

const createColumns = (
  refresh: () => void,
  showModal: (id: number) => void
): ColumnsType<API.OrdersStruct> => [
  {
    title: (
      <div>
        <div className={'mb-2  font-bold'}>商品信息</div>
        <div className={'text-xs flex items-center justify-center'}>
          <div className={'w-[60%] font-bold '}>商品信息</div>
          <div className={'border-x  font-bold w-[20%]'}>数量</div>
          <div className={'w-[20%] font-bold '}>单价</div>
        </div>
      </div>
    ),
    key: 'goods_info',
    align: 'center',
    render: (_, orders) => {
      return (
        orders.orders_detail &&
        orders.orders_detail.length > 0 &&
        orders.orders_detail.map((data) => (
          <div
            className={
              'flex justify-center flex-1 py-3 items-center min-w-[300px]'
            }
            key={data.goods_id}
          >
            <div className={'flex justify-center flex-1 items-center'}>
              <img
                className={'w-10 h-16'}
                src={formatUrl(data.goods?.cover!)}
                alt=""
              />
              <div className={'text-left'}>
                <div className={'px-4 pb-2 pt-3 space-y-1.5'}>
                  <Link
                    to={`/goods_detail/` + data.goods_id}
                    className={'text-xs truncate'}
                  >
                    {data.goods?.title}
                  </Link>
                  <div className={'text-xs truncate-2'}>
                    {data.goods?.description}
                  </div>
                </div>
              </div>
            </div>
            <div className={'flex justify-around items-center w-[40%]'}>
              <div>{data.num}</div>
              <div>
                <em className={'text-xs'}>￥</em>
                {data.price}
              </div>
            </div>
          </div>
        ))
      );
    },
  },
  {
    title: <div className={'font-bold'}>实付款</div>,
    dataIndex: 'amount',
    render: (amount: number) => (
      <div className={'text-base text-red-500 font-bold font-serif'}>
        <em className={'text-xs px-0.5'}>￥</em>
        <span>{isNumber(amount) && amount.toFixed(2)}</span>
      </div>
    ),
  },
  {
    title: <div className={'font-bold'}>买家</div>,
    render: (_, orders) => (
      <Link to={'/user_page/' + orders?.user_Id}>
        {orders?.user && orders?.user?.name}
      </Link>
    ),
  },
  {
    title: <div className={'font-bold'}>下单时间</div>,
    dataIndex: 'created_at',
    render: (created_at) => {
      return formatTime(created_at);
    },
  },
  {
    title: <div className={'font-bold'}>订单编号</div>,
    dataIndex: 'order_no',
    render: (order_no) => {
      return <div className={'w-28'}>{order_no}</div>;
    },
  },
  {
    title: <div className={'font-bold'}>支付宝交易号</div>,
    dataIndex: 'trade_no',
    render: (trade_no) => {
      return <div className={'w-28'}>{trade_no}</div>;
    },
  },
  {
    title: <div className={'font-bold'}>交易状态</div>,
    dataIndex: 'status',
    render: (status, data) => (
      <div>
        <Tag color={status === 5 ? 'red' : 'green'}>
          <span className={'text-sm'}>
            {['已下单', '已付款', '已发货', '已收货', '已取消'][status - 1]}
          </span>
        </Tag>
      </div>
    ),
  },
  {
    title: <div className={'font-bold'}>交易操作</div>,
    key: 'operate',
    render: (_, orders) => {
      return (
        orders.status === 2 && (
          <Button
            type={'link'}
            onClick={() => {
              showModal(orders.id);
            }}
          >
            发货
          </Button>
        )
      );
    },
  },
];

const ReceiveOrdersPage: FC<PropsWithChildren<{}>> = () => {
  const [form] = Form.useForm();
  const { tableProps, pagination, search } = useAntdTable(
    (
      { pageSize, current },
      formData: Omit<API.QueryOrders, 'pageSize' | 'current'>
    ) => {
      return resOrdersReceive({
        pageSize,
        current,
        ...formData,
      });
    },
    { form, cacheKey: 'useReceivedCache' }
  );

  const refresh = () => {
    pagination.changeCurrent(pagination.current);
  };

  const { type, changeType, submit } = search;

  const searchForm = (
    <div className={''}>
      <Form form={form} className={'flex'}>
        <Form.Item name="status" initialValue="0" style={itemStyle}>
          <Select onChange={submit}>
            <Select.Option value="0">全部订单</Select.Option>
            <Select.Option value="1">已下单</Select.Option>
            <Select.Option value="2">已付款</Select.Option>
            <Select.Option value="3">已发货</Select.Option>
            <Select.Option value="4">已收货</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item name="query">
          <Input.Search placeholder="请输入商品名" onSearch={submit} />
        </Form.Item>
        <Button type="link" onClick={changeType}>
          更多搜索
        </Button>
      </Form>
    </div>
  );
  const advance = (
    <div>
      <Form form={form} className={'flex'}>
        <Form.Item name="status" initialValue="0" style={itemStyle}>
          <Select onChange={submit}>
            <Select.Option value="0">全部订单</Select.Option>
            <Select.Option value="1">已下单</Select.Option>
            <Select.Option value="2">已付款</Select.Option>
            <Select.Option value="3">已发货</Select.Option>
            <Select.Option value="4">已收货</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item name="query">
          <Input.Search placeholder="请输入商品名" onSearch={submit} />
        </Form.Item>
        <Form.Item name="order_no" style={orderNoStyle}>
          <Input.Search placeholder="请输入订单号" onSearch={submit} />
        </Form.Item>
        <Form.Item name="trade_no">
          <Input.Search placeholder="请输入支付宝交易号" onSearch={submit} />
        </Form.Item>
        <Button type="link" onClick={changeType}>
          精简搜索
        </Button>
      </Form>
    </div>
  );

  const [isModalOpen, setIsModalOpen] = useState({ show: false, id: 0 });
  const showModal = useCallback((id: number) => {
    setIsModalOpen({ show: true, id });
  }, []);
  const handleCancel = useCallback(
    () => setIsModalOpen({ ...isModalOpen, show: false }),
    [isModalOpen]
  );

  const columns = createColumns(refresh, showModal);

  return (
    <div style={style} className={'p-4 hidden-scrollbar'}>
      {type === 'simple' ? searchForm : advance}
      <div className={'rounded-lg overflow-hidden'}>
        <Table columns={columns} rowKey="id" {...tableProps} />
      </div>
      <Modal
        title={'订单发货'}
        open={isModalOpen.show}
        onCancel={handleCancel}
        footer={null}
      >
        <Form
          validateMessages={validateMessage}
          onFinish={(value: any) => {
            isModalOpen.id > 0 &&
              resOrdersPost(isModalOpen.id, value).then(() => {
                message.success('订单发货成功！');
                refresh();
                handleCancel();
              });
          }}
        >
          <Form.Item name={'express_type'} rules={[{ required: true }]}>
            <Select placeholder={'快递公司'}>
              <Select.Option value={'YTO'}>圆通</Select.Option>
              <Select.Option value={'STO'}>申通</Select.Option>
              <Select.Option value={'JTSD'}>极兔</Select.Option>
              <Select.Option value={'HTKY'}>百事</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name={'express_no'} rules={[{ required: true }]}>
            <Input placeholder={'快递单号'} />
          </Form.Item>
          <Form.Item>
            <div className={'text-right pt-2'}>
              <Button htmlType={'submit'} type={'primary'}>
                发货
              </Button>
            </div>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default memo(ReceiveOrdersPage);
